package edu.cuit.jead.mynetdisk.token;

import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import edu.cuit.jead.mynetdisk.entity.User;

import java.util.Date;

public class TokenUtil {
    private static final long EXPIRE_TIME = 10*60*60*1000;
    private static final String TOKEN_SECRET = "123456";

    public static  String sign(User user) {
        String token = null;
        try{
            Date expireAt = new Date(System.currentTimeMillis()+EXPIRE_TIME);
            token = JWT.create()
                    .withIssuer("auto0")
                    .withClaim("Useremail",user.getEmail())
//                    .withAudience(user.getEmail())
                    .withExpiresAt(expireAt)
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        }catch (Exception e){
            e.printStackTrace();
        }
        return token;
    }
    public static boolean verify(String token) {
        try{
            System.out.println(token);
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auto0").build();
            DecodedJWT jwt = verifier.verify(token);
            System.err.println("认证通过");
            System.err.println("Useremail:"+jwt.getClaim("Useremail").asString());
            System.err.println("过期时间："+jwt.getExpiresAt());
            return true;
        }
        catch (Exception e){
            return false;
        }
    }
}
